package com.example.tms.controller;

import com.example.tms.bean.DriverView;
import com.example.tms.bean.MoneyInfo;
import com.example.tms.bean.ReturnInfo;
import com.example.tms.bean.UserView;
import com.example.tms.mapper.MoneyMapper;
import com.example.tms.tools.GlobalParam;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 现金报账
 */
@RestController
public class MoneyController {

    private final MoneyMapper MoneyMapper;

    @Autowired
    public MoneyController(MoneyMapper MoneyMapper) {
        this.MoneyMapper = MoneyMapper;
    }
    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    //查询报账信息(报账id)
    @RequestMapping(value = "money/{xjbzid}",method = RequestMethod.GET)
    public MoneyInfo getMoneyInfo(@PathVariable String xjbzid){
        return MoneyMapper.findByXjbzid(xjbzid);
    }


    //查询报账信息列表
    @RequestMapping(value = "money",method = RequestMethod.GET)
    public ReturnInfo getDeptInfoAll(@RequestParam(required = false, defaultValue = "") String keyname,
                                     @RequestParam(required = false, defaultValue = "") String keyvalue) {
        List<MoneyInfo> result = MoneyMapper.findAll((Root<MoneyInfo> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();
            switch (keyname) {
                case "jsr":
                    list.add(criteriaBuilder.like(root.get("jsr").as(String.class), "%" + keyvalue + "%"));
                    break;
                case "mingmu":
                    list.add(criteriaBuilder.like(root.get("mingmu").as(String.class), "%" + keyvalue + "%"));
                    break;
                default:
                    break;
            }
            list.add(criteriaBuilder.equal(root.get("sfcz").as(Boolean.class),true));
            Predicate[] p = new Predicate[list.size()];
            criteriaQuery.where(criteriaBuilder.and(list.toArray(p)));
            criteriaQuery.orderBy(criteriaBuilder.desc(root.get("lasttime")));
            return criteriaQuery.getRestriction();
        });
        return ReturnInfo.info2(result);
    }

    //新建报账信息
    @RequestMapping(value = "money",method = RequestMethod.POST)
    public List<Map<String,Object>> saveMoneyInfo(@RequestBody MoneyInfo MoneyInfo){
        List<Map<String,Object>>  list = new ArrayList<>();
        Map<String,Object>  map = new HashMap<>();
        if(MoneyInfo.getRiqi().equals("")){
            map.put("riqi", "0");
        }
        if(MoneyInfo.getMingmu().equals("")){
            map.put("mingmu", "0");
        }
        if(MoneyInfo.getJine().equals("")|| !checkMoney(MoneyInfo.getJine())){
            map.put("jine", "0");
        }

        list.add(map);
        if(map.isEmpty()){
            if(MoneyInfo.getJsr()==null||MoneyInfo.getJsr().equals("")){
                Subject subject = SecurityUtils.getSubject();
                UserView userView = (UserView) subject.getPrincipal();
                MoneyInfo.setJsr(userView.getZsxm());
            }
            MoneyInfo.setLasttime(GlobalParam.getTime());
            MoneyInfo.setSfcz(true);
            MoneyMapper.save(MoneyInfo);
            logger.info("新建现金报账"+MoneyInfo.toString());
            //区分名目
            if (MoneyInfo.getMingmu().equals("当日借款")){
                MoneyInfo.setDrjk(MoneyInfo.getJine());
            }else if(MoneyInfo.getMingmu().equals("当日取款")){
                MoneyInfo.setDrqk(MoneyInfo.getJine());
            }else if(MoneyInfo.getMingmu().equals("当日还款")){
                MoneyInfo.setDrhk(MoneyInfo.getJine());
            }else {
                MoneyInfo.setZrye(MoneyInfo.getJine());
            }
        }
        return list;
    }

    //更新报账信息
    @RequestMapping(value = "money",method = RequestMethod.PUT)
    public List<Map<String,Object>> updateMoneyInfo(@RequestBody MoneyInfo MoneyInfo){
        List<Map<String,Object>>  list = new ArrayList<>();
        Map<String,Object>  map = new HashMap<>();
        if(MoneyInfo.getXjbzid().equals("")||MoneyMapper.findByXjbzid(MoneyInfo.getXjbzid())==null){
            map.put("xjbzid", "0");
        }
        if(MoneyInfo.getRiqi().equals("")){
            map.put("riqi", "0");
        }
        if(MoneyInfo.getMingmu().equals("")){
            map.put("mingmu", "0");
        }
        if(MoneyInfo.getJine().equals("")){
            map.put("jine", "0");
        }

        list.add(map);
        if(map.isEmpty()){
            MoneyInfo.setJsr(MoneyMapper.findByXjbzid(MoneyInfo.getXjbzid()).getJsr());
            MoneyInfo.setLasttime(GlobalParam.getTime());
            MoneyInfo.setSfcz(true);
            MoneyMapper.save(MoneyInfo);
            logger.info("更新现金报账"+MoneyInfo.toString());
            //区分名目
            if (MoneyInfo.getMingmu().equals("当日借款")){
                MoneyInfo.setDrjk(MoneyInfo.getJine());
            }else if(MoneyInfo.getMingmu().equals("当日取款")){
                MoneyInfo.setDrqk(MoneyInfo.getJine());
            }else if(MoneyInfo.getMingmu().equals("当日还款")){
                MoneyInfo.setDrhk(MoneyInfo.getJine());
            }else {
                MoneyInfo.setZrye(MoneyInfo.getJine());
            }
        }
        return list;
    }

    //删除报账信息（假删除 报账id）
    @RequestMapping(value = "money/{xjbzid}",method = RequestMethod.DELETE)
    public ReturnInfo deleteMoneyinfo(@PathVariable String xjbzid){
        String b;
        if(xjbzid==null||MoneyMapper.findByXjbzid(xjbzid)==null){
            b = "该现金报账信息不存在！";
        }else{
            MoneyMapper.DeleteByXjbzid(xjbzid);
            b = "删除成功！";
            logger.info("删除现金报账"+xjbzid);
        }
        return ReturnInfo.info1(b);
    }
    //检查金额
    private Boolean checkMoney(String  jine){
        Boolean b = false;
        if(jine.matches("^\\d+$")){
            b = true;
        }
        return b;
    }
}
